package ru.elteam.web.beans.validators;

import org.apache.commons.lang3.StringUtils;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 * @author Nikita.Brazhnikov
 */
@FacesValidator("elteam.validator.Email")
public class EmailValidator implements Validator {

	private static final String EMAIL_PATTERN =
		 "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
			  + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

	@Override
	public void validate(FacesContext facesContext, UIComponent uiComponent, Object o) throws ValidatorException {
		String errorText = null;
		if (o == null) {
			errorText = "Email must not be empty";
		} else {
			String str = (String)o;
			if (StringUtils.isEmpty(str))
				errorText = "Email must not be empty";
			else
				if (!str.matches(EMAIL_PATTERN))
					errorText = "Email string is not valid";
		}
		if (errorText != null) {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, errorText);
			throw new ValidatorException(message);
		}
	}
}
